﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webdiyer.WebControls.Mvc;
using MinistryStandardPlatformWeb.Models;
using MinistryStandardPlatformEntity;
using MinistryStandardPlatformWeb.Controllers.RealTime;
using System.IO;
using System.Text;

namespace MinistryStandardPlatformWeb.Controllers.Reports
{
    [MenuAuthorized("45")]
    public class WarningDetailController : Controller
    {
        //
        // GET: /WarningDetail/
        private MSPGpsDataContext context = new MSPGpsDataContext();
        private MSPDataContext context1 = new MSPDataContext();
        MinistryStandardPlatformBusiness.DBService.DBHelperClient geoHelper = new MinistryStandardPlatformBusiness.DBService.DBHelperClient();


        public ActionResult Index(string startTime, string endTime,string warningTypes)
        {
            ViewBag.StartTime = startTime;
            ViewBag.EndTime = endTime;
            ViewBag.WarningTypes = warningTypes;
            return View();
        }

        public ActionResult Data(string startTime, string endTime, string warningTypes, string vehicles,int pageIndex=1)
        {
            ViewBag.WarningTypes = warningTypes;
            List<string> types = warningTypes.Split(';').ToList();
            List<string> vehicleList=vehicles.Split(';').ToList();

            //报警类型的中文说明
            List<string> typesName = new List<string>();
            foreach(string item in types)
            {
                typesName.Add(CommonDictionary.WarningType[(CommonDictionary.EWarnType)(Convert.ToInt32(item))]);
            }

            ViewBag.TypesName = typesName;
            if (Session["SearchData"] != null)
            {
                return PartialView((Session["SearchData"] as IEnumerable<WarningStatistics>).ToPagedList(pageIndex, CommonDictionary.SmallerPageSize));
            }


            //查找所有报警
            var warnings = from w in context.GpsWarn
                           where vehicleList.Contains(w.simId) &&
                           types.Contains(w.warntype) &&
                           string.Compare(w.warnstarttime, startTime) >= 0 &&
                           string.Compare(w.warnstarttime, endTime) <= 0
                           select new WarningInfo()
                               {
                                   VehicleId = w.vehicleId,
                                   Sim = w.simId,
                                   WarningType = w.warntype
                                   //WarningTime = w.warnstarttime,
                                   //longitude = w.longitude,
                                   //latitude = w.latitude,
                                   //Speed = w.speed
                               };

            List<string> paramaters = new List<string>();
            for (int i = 0; i < vehicleList.Count; i++)
            {
                paramaters.Add(vehicleList[i].ToVarcharSqlParam());
            }
            for (int i = 0; i < types.Count; i++)
            {
                paramaters.Add(types[i].ToVarcharSqlParam());
            }
            paramaters.Add(startTime.ToVarcharSqlParam());
            paramaters.Add(endTime.ToVarcharSqlParam());
            string warningsJsonStr = RealTimeGet.getReportFromGeoBase(CommonFunctions.GetLoginUser().UserId, CommonFunctions.GetSQL(warnings, paramaters), startTime, endTime, "0");
            List<WarningInfo> warningList = CommonFunctions.JsonStrToObject<List<WarningInfo>>(warningsJsonStr);


            //开始统计
            List<WarningStatistics> warninngStatistics = new List<WarningStatistics>();

            ////首先获取每个单位的报警数
            //var wl= from w in warningList
            //        group w by new {w.Sim,w.VehicleId}
            //        into wg
            //        orderby wg.Key.VehicleId
            //        select new WarningStatistics()
            //        {
            //            Sim=wg.Key.Sim,
            //            VehicleId=wg.Key.VehicleId,
            //            TotalWarningCount=wg.Count()
            //        };
            //warninngStatistics=wl.ToList();

            //获取车牌号（有的车没有警报，从警报表中读不到车牌号）
            var vehicleId = from v in context1.InfoVehicle
                       where vehicleList.Contains(v.SIM)
                       select new WarningInfo()
                       {
                           VehicleId = v.VehicleId,
                           Sim = v.SIM
                       };
            List<WarningInfo> vehicleIdList = vehicleId.ToList();
            foreach (string item in vehicleList)
            {
                WarningStatistics sta = new WarningStatistics();
                sta.Sim = item;
                sta.TypeWarningCount = new List<int>();

                //警报总数
                sta.TotalWarningCount = (from w in warningList where w.Sim==sta.Sim select w.Sim).Count();
                sta.VehicleId = (from v in vehicleIdList where v.Sim == sta.Sim select v.VehicleId).FirstOrDefault();
                //各个类型的警报数
                foreach (string type in types)
                {
                    int count = (from w in warningList where w.WarningType == type && w.Sim == sta.Sim select w.Sim).Count();
                    sta.TypeWarningCount.Add(count);
                }

                warninngStatistics.Add(sta);
            }
            Session["SearchData"] = warninngStatistics;
            return PartialView(warninngStatistics.ToPagedList(pageIndex,CommonDictionary.SmallerPageSize));
        }

        public ActionResult Detail(string sim, string startTime, string endTime, string warningTypes)
        {
            List<string> types = warningTypes.Split(';').ToList();

            var warnings = from w in context.GpsWarn
                           where w.simId==sim &&
                           types.Contains(w.warntype) &&
                           string.Compare(w.warnstarttime, startTime) >= 0 &&
                           string.Compare(w.warnstarttime, endTime) <= 0
                           orderby w.vehicleId,w.warnstarttime
                           select new WarningInfo()
                           {
                               VehicleId = w.vehicleId,
                               Sim = w.simId,
                               WarningType = w.warntype,
                               WarningTime = w.warnstarttime,
                               longitude = w.longitude,
                               latitude = w.latitude,
                               //Speed = w.speed
                           };

            List<string> paramaters = new List<string>();
            paramaters.Add(sim.ToVarcharSqlParam());
            for (int i = 0; i < types.Count; i++)
            {
                paramaters.Add(types[i].ToVarcharSqlParam());
            }
            paramaters.Add(startTime.ToVarcharSqlParam());
            paramaters.Add(endTime.ToVarcharSqlParam());
            string warningsJsonStr = RealTimeGet.getReportFromGeoBase(CommonFunctions.GetLoginUser().UserId, CommonFunctions.GetSQL(warnings, paramaters), startTime, endTime, "0");
            List<WarningInfo> warningList = CommonFunctions.JsonStrToObject<List<WarningInfo>>(warningsJsonStr);

            //获取车辆的所属单位
            var unit = from v in context1.InfoVehicle
                       from u in context1.InfoUnit
                       where v.SIM == sim &&
                       v.ParentUnitId == u.UNITID
                       select new WarningInfo()
                       {
                           VehicleId = v.VehicleId,
                           ParentUnitName = u.UNITNAME,
                           Sim = v.SIM,
                       };
            var wulist = from w in warningList
                       join u in unit
                       on w.VehicleId equals u.VehicleId
                       into wu
                       from wud in wu.DefaultIfEmpty()
                       select new WarningInfo()
                       {
                           VehicleId = w.VehicleId,
                           Sim = w.Sim,
                           WarningType = w.WarningType,
                           WarningTypeName = CommonDictionary.WarningType[(CommonDictionary.EWarnType)(Convert.ToInt32(w.WarningType))],
                           WarningTime = w.WarningTime,
                           longitude = w.longitude,
                           latitude = w.latitude,
                           ParentUnitName=wud.ParentUnitName,
                           POI=w.POI
                       };
            warningList = wulist.ToList();
            return PartialView(warningList);
        }

        public ActionResult GetPoi(List<string> longList, List<string> latiList)
        {
            if (longList == null || latiList == null)
            {
                return Json(null);
            }
            List<string> pois = new List<string>();

            for (int i = 0; i < longList.Count; i++)
            {
                pois.Add(geoHelper.GgpsTranslate2BaiduPoi(longList[i], latiList[i]));
            }

            return Json(pois);

        }


        public ActionResult ExportData(string warningTypes)
        {
            CommonController controller = new CommonController();

            if (Session["SearchData"] != null)
            {
                List<string> types = warningTypes.Split(';').ToList();
                List<WarningStatistics> warnings = Session["SearchData"] as List<WarningStatistics>;

                StringBuilder sb = new StringBuilder();
                sb.Append("<table border='1' cellspacing='0' cellpadding='0'>");
                //-------------------------------表头读取开始------------------------------------------------

                sb.Append("<tr><th>车牌号</th><th>Sim卡号</th><th>警报总数</th>");

                try
                {
                    foreach (string item in types)
                    {
                        sb.Append("<th>"+ CommonDictionary.WarningType[((CommonDictionary.EWarnType)(Convert.ToInt32(item)))] + "</th>");
                    }
                    sb.Append("</tr>");

                    foreach (WarningStatistics item in warnings)
                    {
                        sb.Append("<tr>");
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.VehicleId + "</td>");
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.Sim + "</td>");
                        sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + item.TotalWarningCount.ToString() + "</td>");
                        foreach(int i in item.TypeWarningCount)
                        {
                            sb.Append("<td style='vnd.ms-excel.numberformat:@;'>" + i.ToString() + "</td>");
                        }
                        sb.Append("</tr>");
                    }
                    sb.Append("</table");
                    //------------------------------------------end----------------------------------------------------------------------------------

                    byte[] b = Encoding.GetEncoding("GB2312").GetBytes((sb.ToString()));
                    return File(b, @"application/ms-excel", Server.UrlPathEncode("报警统计" + ".xls"));//输出档案给Client端
                }
                catch
                {
                    ViewBag.Message = "导出出错";
                    return View("ActionResult");
                }  
            }
            else
            {
                ViewBag.Message = "数据已过期，请重新查询";
                return View("ActionResult");
            }
        }
    }
}
